package com.shenmazong.servereduuser.utils;


import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class AuthCodeUtil {
	
//	public static void main(String[] args) {
//		String code = getCode("abc-g-nox-z", 6);
//		System.out.println(code);
//	}
	
	public static String getCode(String content, Integer size) {
		
		char[] charArray = content.toCharArray();
		for (int j = charArray.length-1; j>=0; j--) {
			Character c = charArray[j];
			if("-".equals(c.toString())) {
				char q = charArray[j-1];
				char h = charArray[j+1];
				String cont = "";
				
				int i = 0, k = h-q-1;
				for(i=q+1;i<h;i++) {
					cont += (char)i;
				}
				
				String qq = content.substring(0,j);
				String hh = content.substring(j+1);
				content = qq+cont+hh;
				charArray = content.toCharArray();
				j = j+k;
			}
		}
//		if(content.indexOf("-")!=-1) {
//			char q = charArray[content.indexOf("-")-1];
//			char h = charArray[content.indexOf("-")+1];
//			String cont = "";
//			for(int i=q+1;i<h;i++) {
//				cont += (char)i;
//			}
//			content = content.replace("-", cont);
//		}
		
		String randomcode = "";
		// 用字符数组的方式随机
		String model = content;
		char[] m = model.toCharArray();
		for (int j = 0; j <  size; j++) {
			char c = m[(int) (Math.random() * content.length())];
			// 保证六位随机数之间没有重复的
			if (randomcode.contains(String.valueOf(c))) {
				j--;
				continue;
			}
			randomcode = randomcode + c;
		}
		return randomcode;
	}

	public static void sendMsgToPhone(String code, String phone) {
		String host = "https://smssend.shumaidata.com";
		String path = "/sms/send";
		String method = "POST";
		String appcode = "21f41e905769425caf8638d01229cc4f";//你自己的AppCode
		Map<String, String> headers = new HashMap<String, String>();
		// 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		headers.put("Authorization", "APPCODE " + appcode);
		Map<String, String> querys = new HashMap<String, String>();
		querys.put("receive", phone);//电话号： 你要发给谁
		querys.put("tag", code);//验证码： 内容
		querys.put("templateId", "M09DD535F4");//短信模板
		Map<String, String> bodys = new HashMap<String, String>();

		try {
			/**
			 * 重要提示如下: HttpUtils请从
			 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
			 * 下载
			 *
			 * 相应的依赖请参照
			 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
			 */
			HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
			System.out.println(response.toString());
			// 获取response的body
			System.out.println(EntityUtils.toString(response.getEntity()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}